
# -*- coding: utf-8 -*-
import os

from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtGui import QIcon
from PyQt5.QtWidgets import QDockWidget, QAction, QFileDialog
import cv2
import numpy as np
import copy
from imageManager import *


class gapGui(QtWidgets.QWidget):
    update_signal = QtCore.pyqtSignal(QtGui.QImage)

    def __init__(self, parent=None):
        super(gapGui, self).__init__(parent)
        self.imgMat = None
        self.initUI()
        self.imgMat = copy.deepcopy(img_mng.img)

    def initUI(self):
        positionLabel = QtWidgets.QLabel()
        positionLabel.setText("position:")
        self.positionText = QtWidgets.QLineEdit("0")
        hlayout1 = QtWidgets.QHBoxLayout()
        hlayout1.addWidget(positionLabel)
        hlayout1.addWidget(self.positionText)

        angelLabel = QtWidgets.QLabel()
        angelLabel.setText("angle:")
        self.angelText = QtWidgets.QLineEdit("0")
        hlayout2 = QtWidgets.QHBoxLayout()
        hlayout2.addWidget(angelLabel)
        hlayout2.addWidget(self.angelText)


        okbtn = QtWidgets.QPushButton()
        okbtn.setText("calc")

        vlayout= QtWidgets.QVBoxLayout(self)
        vlayout.addLayout(hlayout1,1)
        vlayout.addStretch(1)
        vlayout.addLayout(hlayout2)
        vlayout.addStretch(1)
        vlayout.addWidget(okbtn)
        okbtn.clicked.connect(self.okbtn_clicked)

    def okbtn_clicked(self):
        if self.imgMat is None:
            return
        imgray = cv2.cvtColor(self.imgMat, cv2.COLOR_BGR2GRAY)
        ret, thresh = cv2.threshold(imgray, 127, 255, 1)
        # cv2.imshow("dd", thresh)
        # cv2.waitKey(0)
        contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
        len_contours = len(contours)
        for i in range(len_contours):
            ret = cv2.fitEllipse(contours[i])
            xc, yc = ret[0]
            b, a = ret[1]
            # print(xc,yc,a,b)
            min_distance = 0xfffffff
            xmin=0
            ymin=0
            for p in contours[i]:
                x,y = p[0]
                distance = (4*(x-xc)*(x-xc)/(a*a) + 4*(y-yc)*(y-yc)/(b*b))
                if distance < min_distance:
                    xmin = x
                    ymin = y
                    min_distance = distance
                print(4*(x-xc)*(x-xc)/(a*a) + 4*(y-yc)*(y-yc)/(b*b))
        cv2.circle(self.imgMat, (xmin,ymin),10, (0,0,255),0)
        self.positionText.setText("{},{}".format(xmin, ymin))
        self.angelText.setText("{}".format(np.arctan2(ymin-yc,xmin-xc)*180/np.pi))
        cv2.drawContours(self.imgMat, contours, -1, (0,255,0), 3)
        qimg = self.convertQtImg(self.imgMat)
        self.update_signal.emit(qimg)

if __name__ == "__main__":
    import sys

    app = QtWidgets.QApplication(sys.argv)
    ui = gapGui()
    ui.initUI()
    ui.show()
    sys.exit(app.exec_())
